package com.smartcampusbackend.util;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Component
public class FileUploadUtil {

    // 文件上传根目录
    private static final String UPLOAD_DIR = "uploads";
    private static final String AVATAR_DIR = "avatars";
    private static final String RESOURCE_DIR = "resources";

    /**
     * 上传头像文件
     * @param file 上传的文件
     * @return 文件访问路径
     * @throws IOException
     */
    public static String uploadAvatar(MultipartFile file) throws IOException {
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IllegalArgumentException("只能上传图片文件");
        }

        // 检查文件大小 (限制为2MB)
        if (file.getSize() > 2 * 1024 * 1024) {
            throw new IllegalArgumentException("文件大小不能超过2MB");
        }

        // 创建上传目录
        String uploadPath = UPLOAD_DIR + File.separator + AVATAR_DIR;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID().toString() + fileExtension;

        // 保存文件
        Path filePath = Paths.get(uploadPath, fileName);
        Files.copy(file.getInputStream(), filePath);

        // 返回文件访问路径
        return "/" + uploadPath.replace(File.separator, "/") + "/" + fileName;
    }

    /**
     * 上传资源文件
     * @param file 上传的文件
     * @return 文件访问路径
     * @throws IOException
     */
    public static String uploadResourceFile(MultipartFile file) throws IOException {
        // 检查文件大小 (限制为100MB)
        if (file.getSize() > 100 * 1024 * 1024) {
            throw new IllegalArgumentException("文件大小不能超过100MB");
        }

        // 创建上传目录
        String uploadPath = UPLOAD_DIR + File.separator + RESOURCE_DIR;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID().toString() + fileExtension;

        // 保存文件
        Path filePath = Paths.get(uploadPath, fileName);
        Files.copy(file.getInputStream(), filePath);

        // 返回文件访问路径
        return "/" + uploadPath.replace(File.separator, "/") + "/" + fileName;
    }

    /**
     * 上传图片文件（通用方法，支持更大的文件大小）
     * @param file 上传的文件
     * @param subDir 子目录名称
     * @return 文件访问路径
     * @throws IOException
     */
    public static String uploadImage(MultipartFile file, String subDir) throws IOException {
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IllegalArgumentException("只能上传图片文件");
        }

        // 检查文件大小 (限制为5MB)
        if (file.getSize() > 5 * 1024 * 1024) {
            throw new IllegalArgumentException("文件大小不能超过5MB");
        }

        // 创建上传目录
        String uploadPath = UPLOAD_DIR + File.separator + subDir;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID().toString() + fileExtension;

        // 保存文件
        Path filePath = Paths.get(uploadPath, fileName);
        Files.copy(file.getInputStream(), filePath);

        // 返回文件访问路径
        return "/" + uploadPath.replace(File.separator, "/") + "/" + fileName;
    }

    /**
     * 保存文件到指定路径
     * @param file 上传的文件
     * @param relativePath 相对路径
     * @return 文件访问路径
     * @throws IOException
     */
    public static String saveFile(MultipartFile file, String relativePath) throws IOException {
        // 检查文件大小 (限制为10MB)
        if (file.getSize() > 10 * 1024 * 1024) {
            throw new IllegalArgumentException("文件大小不能超过10MB");
        }

        // 创建上传目录
        String uploadPath = UPLOAD_DIR + File.separator + relativePath.substring(0, relativePath.lastIndexOf("/"));
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 保存文件
        Path filePath = Paths.get(uploadPath, relativePath.substring(relativePath.lastIndexOf("/") + 1));
        Files.copy(file.getInputStream(), filePath);

        // 返回文件访问路径
        return "/" + uploadPath.replace(File.separator, "/") + "/" + relativePath.substring(relativePath.lastIndexOf("/") + 1);
    }

    /**
     * 删除文件
     * @param filePath 文件路径
     */
    public static void deleteFile(String filePath) {
        if (filePath != null && !filePath.isEmpty()) {
            try {
                // 移除开头的斜杠
                if (filePath.startsWith("/")) {
                    filePath = filePath.substring(1);
                }

                File file = new File(filePath);
                if (file.exists()) {
                    file.delete();
                }
            } catch (Exception e) {
                // 记录日志但不抛出异常
                System.err.println("删除文件失败: " + filePath + ", 错误: " + e.getMessage());
            }
        }
    }

    /**
     * 删除头像文件
     * @param avatarPath 头像路径
     */
    public static void deleteAvatar(String avatarPath) {
        if (avatarPath != null && !avatarPath.isEmpty()) {
            try {
                // 移除开头的斜杠
                if (avatarPath.startsWith("/")) {
                    avatarPath = avatarPath.substring(1);
                }

                File file = new File(avatarPath);
                if (file.exists()) {
                    file.delete();
                }
            } catch (Exception e) {
                // 记录日志但不抛出异常
                System.err.println("删除头像文件失败: " + avatarPath + ", 错误: " + e.getMessage());
            }
        }
    }

    /**
     * 检查文件是否为有效的图片
     * @param file 文件
     * @return 是否为有效图片
     */
    public static boolean isValidImage(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return false;
        }

        String contentType = file.getContentType();
        return contentType != null && (contentType.equals("image/jpeg") ||
                contentType.equals("image/png") ||
                contentType.equals("image/gif"));
    }


    /**
     * 检查文件是否为有效的附件
     * @param file 文件
     * @return 是否为有效附件
     */

    /**
     * 上传附件文件（无类型/大小限制）
     * @param file 上传的文件
     * @return 文件访问路径
     * @throws IOException
     */
    public static String uploadAttachment(MultipartFile file) throws IOException {
        // 创建上传目录
        String uploadPath = UPLOAD_DIR + File.separator + "attachments";
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID().toString() + fileExtension;

        // 保存文件
        Path filePath = Paths.get(uploadPath, fileName);
        Files.copy(file.getInputStream(), filePath);

        // 返回文件访问路径
        return "/" + uploadPath.replace(File.separator, "/") + "/" + fileName;
    }
}